<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>非父子组件间的传值</title>
  <script src="./vue.js"></script>
</head>

<body>
  <div id="root">
    <child content="2019"></child>
    <child content="2020"></child>
  </div>

  <script>
    // 兄弟组件传值：点击组件a，组件b的内容也变成a的，点击b同理
    Vue.prototype.bus = new Vue()

    Vue.component("child", {
      data: function() {
        return {
          selfContent: this.content
        }
      },
      props:{
        content: String
      },
      template: '<div @click="handleClick">{{selfContent}}</div>',
      methods: {
        handleClick: function() {
          // alert(this.content)
          this.bus.$emit("change", this.selfContent) // 事件发布
        }
      },
      mounted: function() {
        var _this = this;
        this.bus.$on('change', function(msg) {  // 事件订阅
          // alert(msg)
          _this.selfContent = msg;
        })
      }
    })

    var vm = new Vue({
      el: "#root",
    })

  </script>
</body>

</html>